package com.xm.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器，
 * 拦截器名LoginFilter
 * 拦截的地址：/admin/*  表示后台的所有请求
 * @author tyf
 *
 */
@WebFilter(filterName="LoginFilter",urlPatterns="/admin/*")
public class LoginFilter implements Filter{
	

	/**
	 * 执行过滤
	 */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpServletResponse servletResponse = (HttpServletResponse) response;
		HttpSession session = servletRequest.getSession();

		String path = servletRequest.getRequestURI();
		System.out.println("请求地址"+path);
		
		// 登陆页面无需过滤
		if (path.indexOf("/login.jsp") > -1 || path.indexOf("/UserServletAdmin") > -1) {
			chain.doFilter(servletRequest, servletResponse);//放行
			System.out.println("登录页面和登录请求，放行！");
			return;
		}
		
		String user = (String) session.getAttribute("username");
		// 判断如果没有取到员工信息,就跳转到登陆页面
		if (user == null || "".equals(user)) {
			System.out.println("session未存储用户信息,跳转到登陆页面");
			servletResponse.sendRedirect("../admin/login.jsp");
		} else {
			// 已经登陆,继续此次请求
			chain.doFilter(request, response);
			System.out.println("已经登陆,放行");
		}
	}

    
	@Override
	public void destroy() {
		System.out.println("销毁时执行");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("初始化时执行");
	}


}

